import XLSX from 'xlsx'

// 导出excel文件工具方法
// datas | Array: 需要导出的数据数组，默认按字段顺序依次生成表头，必传
// filename | String: 导出的excel名称，可加.xlsx后缀也可不加，默认导出格式为.xlsx
// headerorder | Array: 需要调整的表头顺序字段，优先级高于数据默认字段顺序，可传部分，那么部分表头数据就提前显示，非必传
// sheetname | String: 工作表名称，非必传
export function ExportHistoricalStatistics (datas, filename, headerorder, sheetname) {
  let wb = XLSX.utils.book_new()
  let sheetconfigs = {
    skipHeader: false
  }
  if (headerorder !== undefined && headerorder instanceof Array) {
    sheetconfigs.header = headerorder
  }
  let contentsWs = XLSX.utils.json_to_sheet(datas, sheetconfigs)
  if (sheetname !== undefined && typeof (sheetname) === 'string' && sheetname !== '') {
    XLSX.utils.book_append_sheet(wb, contentsWs, sheetname)
  } else {
    XLSX.utils.book_append_sheet(wb, contentsWs)
  }
  if (filename === undefined || filename === '') {
    XLSX.writeFile(wb, 'export.xlsx')
  } else if (filename.indexOf('.xlsx') === -1) {
    XLSX.writeFile(wb, filename + '.xlsx')
  } else {
    XLSX.writeFile(wb, filename)
  }
}
